package work.linruchang.oauthresourceproject.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 增强的Spring处理工具
 *
 * @author LinRuChang
 * @version 1.0
 * @date 2022/04/02
 * @since 1.8
 **/
public class EnhanceSpringUtil extends SpringUtil {

    /**
     * 静态获取当前的请求对象
     *
     * @return
     */
    public static HttpServletRequest getCurrrentRequest() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            return request;
        } catch (Exception e) {

            return null;
        }
    }

    public static HttpServletResponse getCurrentResponse() {
        try {
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            return response;
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 获取当前请求中的表单参数 【getParameter级别】
     * key value
     *
     * @return
     */
    public static Map getCurrrentRequestRequestParameterMap() {
        HttpServletRequest currrentRequest = getCurrrentRequest();
        if (currrentRequest != null) {
            return currrentRequest.getParameterMap();
        } else {
            return Collections.emptyMap();
        }
    }

    /**
     * 获取当前请求中的表单参数
     * 某key的value值含有多个，仅取第一个
     *
     * @return
     */
    public static Map getCurrrentRequestRequestParameterOneValueMap() {
        Map currrentRequestRequestParameterMap = getCurrrentRequestRequestParameterMap();
        if (CollUtil.isNotEmpty(currrentRequestRequestParameterMap)) {
            Set<Map.Entry> entries = currrentRequestRequestParameterMap.entrySet();
            for (Map.Entry entry : entries) {
                boolean arrayFlag = ArrayUtil.isArray(entry.getValue());
                if (arrayFlag && ArrayUtil.length(entry.getValue()) > 0) {
                    entry.setValue(((Object[]) (entry.getValue()))[0]);
                }
            }
        }
        return currrentRequestRequestParameterMap;
    }


    /**
     * 获取形参请求httpServletRequest如果为空，则获取当前请求的全部的属性 【getAttribute级别】
     *
     * @return
     */
    public static Map getCurrentRequestAttribute(HttpServletRequest httpServletRequest) {
        if (httpServletRequest == null) {
            httpServletRequest = getCurrrentRequest();
        }

        Map result = Collections.emptyMap();
        if (httpServletRequest != null) {
            Enumeration attributeNames = httpServletRequest.getAttributeNames();
            while (attributeNames.hasMoreElements()) {
                Object attributeNameObj = attributeNames.nextElement();
                String attributeNameStr = null;
                if (attributeNameObj != null && attributeNameObj instanceof String) {
                    result = CollUtil.isEmpty(result) ? new HashMap() : result;
                    attributeNameStr = (String) attributeNameObj;
                }
                if (!StrUtil.containsAny(attributeNameStr, "org.springframework", "encodingFilter")) {
                    result.put(attributeNameStr, httpServletRequest.getAttribute(attributeNameStr));
                }
            }
        }
        return result;
    }

    /**
     * 获取当前请求全部的属性 【getAttribute级别】
     *
     * @return
     */
    public static Map getCurrentRequestAttribute() {
        return getCurrentRequestAttribute(null);
    }


    /**
     * 获取形参请求httpServletRequest如果为空，则获取当前请求的会话session全部的属性 【getAttribute级别】
     *
     * @return
     */
    public static Map getCurrentSessionAttribute(HttpServletRequest httpServletRequest) {
        if (httpServletRequest == null) {
            httpServletRequest = getCurrrentRequest();
        }

        Map result = Collections.emptyMap();
        if (httpServletRequest != null) {
            Enumeration attributeNames = httpServletRequest.getSession().getAttributeNames();
            while (attributeNames.hasMoreElements()) {
                Object attributeNameObj = attributeNames.nextElement();
                String attributeNameStr = null;
                if (attributeNameObj != null && attributeNameObj instanceof String) {
                    result = CollUtil.isEmpty(result) ? new HashMap() : result;
                    attributeNameStr = (String) attributeNameObj;
                }
                if (!StrUtil.containsAny(attributeNameStr, "org.springframework", "encodingFilter")) {
                    result.put(attributeNameStr, httpServletRequest.getSession().getAttribute(attributeNameStr));
                }
            }
        }
        return result;
    }

    /**
     * 获取当前请求的会话session全部的属性 【getAttribute级别】
     *
     * @return
     */
    public static Map getCurrentSessionAttribute() {
        return getCurrentSessionAttribute(null);
    }


    /**
     * 命令浏览器删除某个cookie
     *
     * @param cookieName
     * @return
     */
    public static Cookie delCookie(String cookieName) {
        Assert.notBlank(cookieName, "cookie名不能缺失，请检查");

        Cookie cookie = new Cookie(cookieName, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);

        Optional.ofNullable(getCurrentResponse())
                .ifPresent(response -> response.addCookie(cookie));
        return cookie;
    }
}
